﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Project.Core.Config.Entity.Dto;
using System.Security.Claims;

namespace Project.Core.Config.Controllers {
    [ApiController]
    public class ApiController : ControllerBase {

        //public ILogger logger { get; set; }

        /// <summary>
        /// 获取页面信息
        /// </summary>
        /// <returns></returns>
        protected Page GetPage() {
            string current = HttpContext.Request.Query["current"];
            current = current.IsNullOrEmpty() ? "1" : current;
            string size = HttpContext.Request.Query["size"];
            size = size.IsNullOrEmpty() ? "10" : size;

            return new Page(int.Parse(current), int.Parse(size));
        }

        /// <summary>
        /// 权限判断
        /// </summary>
        /// <param name="roleType"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        protected string Authorization(string roleType, int roleId) {
            var roles = HttpContext.User.Claims.Where(x => x.Type == ClaimTypes.Role).Select(x => x.Value).ToList();
            if (!roles.Contains("admin")) {
                var claim = HttpContext.User.Claims.FirstOrDefault(x => x.Type == roleType);
                if (claim == null) {
                    return $"你没有{roleType}的权限，操作失败";
                } else {
                    var roleids = claim.Value.Split(',')
                                        .Select(s => int.Parse(s))
                                        .ToList();

                    if (!roleids.Contains(roleId)) return $"你没有权限执行该操作，如需继续操作请联系管理员";
                }
            }
            return "";
        }
    }
}
